package celiasoft.itasalib.structures;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import celiasoft.itasalib.query.resultparser.MalformedEpisodeDataException;

public class EpisodeData {
	
	@Override
	public String toString() {
		String format = (this._episode > 99)?"S%02dE%03d":"S%02dE%02d";
				
		return String.format(format, this._season, this._episode);
	}


	private int _season;
	private int _episode;
	
	public EpisodeData(int season, int episode) {
		super();
		_season = season;
		_episode = episode;
	}
	
	/**
	 * @return the season
	 */
	public int getSeason() {
		return _season;
	}
	/**
	 * @param season the season to set
	 */
	public void setSeason(int season) {
		_season = season;
	}
	/**
	 * @return the episode
	 */
	public int getEpisode() {
		return _episode;
	}
	/**
	 * @param episode the episode to set
	 */
	public void setEpisode(int episode) {
		_episode = episode;
	}
	
	
	public static EpisodeData parse(String strValue) throws MalformedEpisodeDataException{
		
        String completePattern = "([sS][0-9]{1,3}[eE][0-9]{1,3})|([0-9]{1,3}[xX ][0-9]{1,3})";
        String singlePattern = "([0-9]{1,3})";
    	String[] res = new String[2];
		int c;
    	
		if(strValue == null || !strValue.matches(completePattern)){
			
			throw new MalformedEpisodeDataException();
		}
	
		Pattern p = Pattern.compile(singlePattern);
        Matcher m = p.matcher(strValue);
        
        for(c = 0; m.find(); c++){
        	 res[c] =  m.group(c);
        }
        
        if(c != 2){
			throw new MalformedEpisodeDataException();
 
        }
        
        int season = Integer.parseInt(res[0]);
        int episode = Integer.parseInt(res[1]);
        
		return new EpisodeData(season, episode);
	}
	
}
